package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.StringUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;

/**
 * 我的预约
 * Created by gaoge on 2016/12/13.
 */
public class MyOrderActivity extends BaseActivity implements View.OnClickListener,MyListView.IXListViewListener {

    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //显示数据的listview
    private MyListView listview = null;
    //listview适配器
    private ListviewAdapter listviewAdapter = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //保存数据集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog zhuce_dialog;
    //数据库
    private DBManager db=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myorder_list);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，给相应组件添加点击事件
     */
    private void initialization() {
        db=new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        listview = (MyListView) findViewById(R.id.listview);
        title_name.setText("我的预约");
        img_back.setOnClickListener(this);
    }

    /**
     * 功能实现
     */
    private void realize() {

        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            zhuce_dialog = new MyAlertDialog().ShowDialog(MyOrderActivity.this, R.layout.dialog_loading);
            zhuce_dialog.setCancelable(true);
            getListData();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
        }
    }

    /**
     * 下载列表数据
     */
    public void getListData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.MyOrder(currentPage,number)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code==200||code==204) {
                        JSONObject jsonObject = JSONUtil.strToJson(bodys);
                        //获取数据总量
                        if (totalCount == 0) {
                            totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
                        }
                        bodys = jsonObject.get("items").toString();
                        if (bodys != null && !bodys.equals("") && !bodys.equals("[]")) {
                            JSONArray jsonArray = new JSONArray(bodys);
                            list.addAll(JSONUtil.jsonAryToListMap(jsonArray));
                            loginHandler.sendEmptyMessage(1);
                        } else {
                            loginHandler.sendEmptyMessage(2);
                        }
                    }else{
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    loginHandler.sendEmptyMessage(2);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (zhuce_dialog != null) {
                zhuce_dialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    listview.setPullLoadEnable(true);
                    listview.setXListViewListener(MyOrderActivity.this, totalCount, currentPage, number);
                    if (listviewAdapter == null) {
                        listview.setVisibility(MyListView.VISIBLE);
                        no_data_linearlayout.setVisibility(LinearLayout.GONE);
                        listviewAdapter = new ListviewAdapter(MyOrderActivity.this, list, imageLoader, options);
                        listview.setAdapter(listviewAdapter);
                    } else {
                        onLoad();
                        listviewAdapter.notifyDataSetChanged();
                    }
                    break;
                case 2:
                    no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                    listview.setVisibility(MyListView.GONE);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 分类列表适配器
     */
    class ListviewAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;
        private ImageLoader imageLoader = null;
        private DisplayImageOptions options = null;

        public ListviewAdapter(Context context,
                               ArrayList<HashMap<String, String>> getData, ImageLoader loader,
                               DisplayImageOptions options) {
            lf = LayoutInflater.from(context);
            this.imageLoader = loader;
            this.options = options;
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.myorder_item, null);
                viewHolder.activity_doctorlist_iv = (ImageView) convertView.findViewById(R.id.activity_doctorlist_iv);
                viewHolder.code = (TextView) convertView.findViewById(R.id.code);
                viewHolder.user_name = (TextView) convertView.findViewById(R.id.user_name);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.position = (TextView) convertView.findViewById(R.id.position);
                viewHolder.office = (TextView) convertView.findViewById(R.id.office);
                viewHolder.activity_doctorlist_grade = (TextView) convertView.findViewById(R.id.activity_doctorlist_grade);
                viewHolder.activity_doctorlist_doctorname = (TextView) convertView.findViewById(R.id.activity_doctorlist_doctorname);
                viewHolder.time = (TextView) convertView.findViewById(R.id.time);
                viewHolder.tall = (TextView) convertView.findViewById(R.id.tall);
                viewHolder.rule = (TextView) convertView.findViewById(R.id.rule);
                viewHolder.relat_ing= (RelativeLayout) convertView.findViewById(R.id.relat_ing);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.code.setText("预约码:"+getData.get(position).get("reservationCode"));
            viewHolder.user_name.setText("预约人:"+getData.get(position).get("userName"));
            viewHolder.name.setText(getData.get(position).get("doctorName"));
            viewHolder.position.setText(getData.get(position).get("doctorProfessionalTitle"));
            viewHolder.office.setText(getData.get(position).get("doctorPrimaryDepartmentName"));
            viewHolder.activity_doctorlist_doctorname.setText(getData.get(position).get("doctorPrimaryHospitalName"));
            viewHolder.activity_doctorlist_grade.setText(getData.get(position).get("doctorPrimaryHospitalLevel"));
            String time=getData.get(position).get("reservationDate").split("T")[0];
            if(getData.get(position).get("time").equals("1")){
                viewHolder.time.setText(time+"上午");
            }else{
                viewHolder.time.setText(time+"下午");
            }
            //设置图片，如果内存中有，优先从内存中读取
            if (getData.get(position).get("doctorPhotoUrl") != null&&!getData.get(position).get("doctorPhotoUrl").equals("")&&!getData.get(position).get("doctorPhotoUrl").equals("null")) {
                imageLoader.displayImage(getData.get(position).get("doctorPhotoUrl"), viewHolder.activity_doctorlist_iv, options);
            }else{
                viewHolder.activity_doctorlist_iv.setImageResource(R.mipmap.doctor_no);
            }
            if (DateUtils.getStringToDate2(time) >= DateUtils.getStringToDate2(DateUtils.getCurrentDate())) {
                viewHolder.relat_ing.setVisibility(RelativeLayout.VISIBLE);
                viewHolder.tall.setText(getData.get(position).get("cancelReservationRule"));
                viewHolder.rule.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showRule(getData.get(position).get("reservationRule"));
                    }
                });
            }else{
                viewHolder.relat_ing.setVisibility(RelativeLayout.GONE);
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private TextView code = null;
        private TextView user_name = null;
        private ImageView activity_doctorlist_iv = null;
        private TextView name = null;
        private TextView position = null;
        private TextView office = null;
        private TextView activity_doctorlist_grade = null;
        private TextView activity_doctorlist_doctorname = null;
        private TextView time = null;
        private TextView tall = null;
        private TextView rule = null;
        private RelativeLayout relat_ing = null;
    }

    //加载框
    MyAlertDialog dialog;

    /**
     * 预约规则
     */
    private void showRule(String ruleString) {
        try {
            //加载弹出框
            dialog = new MyAlertDialog();
            dialog.rule_Dialog(MyOrderActivity.this, R.layout.rule_dialog);
            TextView data = dialog.getData();
            data.setText(StringUtil.ToDBC(ruleString));
            TextView cancel_text = dialog.getCancel_text();
            cancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //上拉加载更多
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        getListData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
}
